using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BrickManager : Singleton<BrickManager>
{
    [SerializeField] private Sprite[] states;
    [SerializeField] private GameObject brickPrefab;
    [SerializeField] private Vector3 originPos = new Vector3(-8, 7, 0);
    [SerializeField] private Vector2 cellOffset = new Vector2(4, -1.5f);

    private int brickNum;
    private List<Brick> brickList = new List<Brick>();

    protected override void Awake()
    {
        base.Awake();
    }

    private void Start() {
        ResetBrick();
    }

    private void OnEnable() {
        EventHandler.AddListener(Events.ResetGame, ResetBrick);
    }

    private void OnDisable() {
        EventHandler.RemoveListener(Events.ResetGame);
    }

    public void ResetBrick()
    {
        int level = GameManager.Instance.NextLevel();
        string fileName = $"level_{level}.json";
        brickNum = 0;
        brickList.Clear();
        if(SaveSystem.SaveFileExit(fileName))
        {
            MapData mapData = SaveSystem.Load<MapData>(fileName);

            for(int i=0; i<mapData.mapList.Count; i++)
            {
                int type = mapData.mapList[i];
                if(type == -1)
                    continue;
                
                SpawnBrick(i, type);
            }
        }
        else
        {
            for(int i=0; i<25; i++)
            {
                SpawnBrick(i, Random.Range((int)0, (int)states.Length));
            }
        }
    }

    private void SpawnBrick(int id, int type)
    {
        int row = id / 5;
        int col = id % 5;
        Vector3 pos = new Vector3(originPos.x + col * cellOffset.x, originPos.y + row * cellOffset.y);
        GameObject obj = PoolManager.Instance.ReuseGO(brickPrefab, pos, Quaternion.identity);

        if(obj.TryGetComponent<Brick>(out Brick brick))
        {
            brick.Init(type, states);
            brickList.Add(brick);
            brickNum++;
        }
    }

    public void SubBrick()
    {
        brickNum--;
        
        if(brickNum == 0)
        {
            EventHandler.Dispatch(Events.NextLevel);
        }
    }

    public void Bug()
    {
        foreach(Brick brick in brickList)
        {
            SubBrick();
            brick.gameObject.SetActive(false);
        }
    }
}
